﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using nyxwin.Main.Base.ViewModels;
using nyxwin.Data.Discussions;
using nyxwin.Common.Settings;
using System.Collections.Generic;
using System.Linq;

namespace nyxwin.Main.ViewModel.SubModels
{
    public class DiscussionViewModel : BaseViewModel
    {
        private static readonly Guid GETPOST_ID = Guid.NewGuid();

        private int id;
        
        public DiscussionViewModel(int id)
        {
            this.id = id;
            this.title = "Not supported yet";

            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                Refresh();
            });
        }

        private List<DiscussionPostViewModel> posts;
        public List<DiscussionPostViewModel> Posts
        {
            get { return posts; }
            set
            {
                posts = value;
                RaisePropertyChanged(() => Posts);
            }
        }

        private void Refresh()
        {
            SetIsInDeterminate(GETPOST_ID, "Getting posts ...");

            var discMgr = new DiscussionManager(ApplicationSettings.Instance.AuthorizationNick, ApplicationSettings.Instance.AuthorizationToken);

            discMgr.ErrorOccurred += new EventHandler<Data.Base.ErrorOccurredEventArgs>(discMgr_ErrorOccurred);
            discMgr.GetDiscussionCompleted += new EventHandler<GetDiscussionEventArgs>(discMgr_GetDiscussionCompleted);

            discMgr.GetDiscussion(new DiscussionQuery(this.id, DiscussionQuery.Newest));
        }

        void discMgr_GetDiscussionCompleted(object sender, GetDiscussionEventArgs e)
        {
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                UnSetInDeterminate(GETPOST_ID);

                if (e.Error)
                    RaiseError(e.ErrorMessage);
                else
                {
                    this.Title = e.Name;
                    this.Posts = e.DiscussionList.Select(x => new DiscussionPostViewModel(x, id)).ToList();
                }
            });
        }

        void discMgr_ErrorOccurred(object sender, Data.Base.ErrorOccurredEventArgs e)
        {
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                UnSetInDeterminate(GETPOST_ID);
                RaiseError(e.ErrorMessage);
            });
        }

        private string title;

        public string Title
        {
            get { return title; }
            set
            {
                title = value;
                RaisePropertyChanged(() => Title);
            }
        }

    }
}
